package com.example.webtest.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@RestController
@RequestMapping("/oauth")
public class RestAuthController {
    @ResponseBody
	@RequestMapping("/revoke")
	public Object revokeAuth(HttpSession httpSession) throws IOException {
		AuthRequest authRequest = getAuthRequest();
		String token=(String)httpSession.getAttribute("token");
		return authRequest.revoke(AuthToken.builder().accessToken(token).build());
	}

	@RequestMapping("/render")
	public void renderAuth(HttpServletResponse response) throws IOException {
		AuthRequest authRequest = getAuthRequest();
		response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
	}
	@ResponseBody
	@RequestMapping("/callback")
	public Object login(AuthCallback callback,HttpSession httpSession) {
		AuthRequest authRequest = getAuthRequest();

		AuthResponse login = authRequest.login(callback);
		JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(login));
		String msg = jsonObject.getString("msg");
		String code = jsonObject.getString("code");
		JSONObject object= JSONObject.parseObject(JSON.toJSONString(jsonObject.get("data")));
		String username = object.getString("username");
		String token= JSONObject.parseObject(JSON.toJSONString(object.get("token"))).getString("accessToken");
		httpSession.setAttribute("token",token);
		System.out.println(httpSession.getAttribute("token"));

		if(code.equals("2000")){
			return "成功";
		}
		return "失败";

	}

	private AuthRequest getAuthRequest() {
		return new AuthGiteeRequest(AuthConfig.builder()
				.clientId("a516c51c56e6286f1d71ee6abfcf8097c4b3f84ae55db53b7deb341be3f6637c")
				.clientSecret("0cb79d8d01088539df763915976646c00efbff65f9fb689de0266bb3df61957d")
				.redirectUri("http://127.0.0.1:8080/oauth/callback")
				.build());
	}


	@RequestMapping("/getToken")
	public String getToken(HttpSession httpSession){
		System.out.println(httpSession.getAttribute("token"));
		return (String)httpSession.getAttribute("token");
	}
}